<template>
	<el-dropdown @command="handleCommand">
		<span class="el-dropdown-link">
			下拉菜单
			<i class="el-icon-arrow-down el-icon--right"></i>
		</span>
		<el-dropdown-menu slot="dropdown">
			<el-dropdown-item :command="item.name" :key="index" v-for="(item, index) in dataTrigger">{{
				item.label
			}}</el-dropdown-item>
		</el-dropdown-menu>
	</el-dropdown>
</template>

<script>
export default {
	name: 'CDropdown',
	props: {
		props: {
			type: Array,
			default: function () {
				return [
					{
						fields: [],
					},
				]
			},
		},
	},
	computed: {
		dataTrigger() {
			if (this.props[1].fields[0].value.dataJson.json) {
				let result = this.props[1].fields[0].value.dataJson.json
				// console.log(this.getResult(result))
				return this.getResult(result)
			}
			return []
		},
		itemWidth() {
			if (this.dataTrigger.length > 1) {
				return 100 / this.dataTrigger.length
			} else {
				return 100
			}
		},
	},
	data() {
		return {
			activeName: '',
		}
	},
	methods: {
		handleCommand(command) {
			//
			this.$message('click on item ' + command)
		},
		getResult(json) {
			let jsonArray = []
			try {
				jsonArray = JSON.parse(json)
			} catch (e) {
				console.warn(e.message)
			}
			let model = this.props[1].fields[0].value.dataJson.model
			let fieldHref = model[0].field
			let mappingHref = model[0].mapping
			let keyHref = mappingHref || fieldHref

			let fieldTitle = model[1].field
			let mappingTitle = model[1].mapping
			let keyTitle = mappingTitle || fieldTitle

			if (jsonArray.length > 0) {
				let outJson = []
				jsonArray.forEach(element => {
					outJson.push({
						name: element[keyHref],
						label: element[keyTitle],
					})
				})
				return outJson
			} else {
				return jsonArray
			}
		},
	},
}
</script>
<style lang="stylus" scoped>
.el-dropdown-link {
	color: #3d88d6;
}
</style>